package com.xxlie.auth.service.impl;

import com.xxlie.core.model.Page;
import com.xxlie.auth.domain.Role;
import com.xxlie.auth.domain.User;
import com.xxlie.auth.domain.UserLoginLog;
import com.xxlie.auth.repository.UserLoginLogRepository;
import com.xxlie.auth.service.UserLoginLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Transactional
@Service
public class UserLoginLogServiceImpl implements UserLoginLogService {
    @Autowired
    UserLoginLogRepository userLoginLogRepository;

    @Override
    public UserLoginLog save(UserLoginLog userLoginLog) {
        return this.userLoginLogRepository.save(userLoginLog);
    }

    @Override
    public Page<UserLoginLog> findAll(Page<UserLoginLog> page, UserLoginLog userLoginLog) {
        Sort sort = new Sort(Sort.Direction.DESC, "createDate");
        PageRequest pageRequest = new PageRequest(page.getPageNumber(), page.getPageSize(), sort);
        org.springframework.data.domain.Page<UserLoginLog> dictPage = userLoginLogRepository.findAll((root, query, builder) -> {

            List<Predicate> predicates = new ArrayList<>();
            predicates.add(builder.like(root.get("delFlag"), Role.DEL_FLAG_NORMAL));
            Predicate[] predicatesArray = new Predicate[predicates.size()];
            predicates.toArray(predicatesArray);
            return builder.and(predicatesArray);

        }, pageRequest);

        return new Page<UserLoginLog>(dictPage);
    }

    @Override
    public int countByUserAndCreateDateAfter(User user, Date createDate) {
        return this.userLoginLogRepository.countByUserAndCreateDateAfter(user, createDate);
    }
}